package config

import (
	"fmt"

	"github.com/spf13/viper"
)

type Config struct {
	Server   ServerConfig
	Database DatabaseConfig
	MQTT     MQTTConfig
	Email    EmailConfig
}

type ServerConfig struct {
	Port int
}

type DatabaseConfig struct {
	Host      string
	Port      int
	Username  string
	Password  string
	DBName    string
	Charset   string
	ParseTime bool
}

type MQTTConfig struct {
	Broker         string
	Username       string
	Password       string
	ClientUsername string
	ClientPassword string
	WebsocketPort  int
}

type EmailConfig struct {
	Host     string
	Port     int
	Username string
	Password string
	Subject  string
}

var GlobalConfig Config

func LoadConfig() error {
	viper.SetConfigName("config")
	viper.SetConfigType("yaml")
	viper.AddConfigPath("config")
	viper.AddConfigPath(".")

	if err := viper.ReadInConfig(); err != nil {
		return fmt.Errorf("failed to read config file: %w", err)
	}

	if err := viper.Unmarshal(&GlobalConfig); err != nil {
		return fmt.Errorf("failed to unmarshal config: %w", err)
	}

	return nil
}
